package com.csx.governance.traffic.core.context.resttemplate;

import com.csx.governance.traffic.core.context.TrafficRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.util.CollectionUtils;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cuisongxu
 * @date 2022/12/3 18:57
 */
public class TrafficRestTemplateRequest extends TrafficRequest implements HttpRequest{

    public TrafficRestTemplateRequest(HttpRequest originRequest) {
        super(originRequest);
    }

    @Override
    public Map<String, String> getSingleValueHeaders() {
        HttpHeaders httpHeaders = getOriginRequest().getHeaders();
        Map<String, String> headers = new HashMap<>(httpHeaders.entrySet().size());
        for (Map.Entry<String, List<String>> entry : httpHeaders.entrySet()) {
            String key = entry.getKey();
            List<String> values = entry.getValue();
            headers.put(key, values.get(0));
        }
        return headers;
    }

    @Override
    public String getFirstHeader(String name) {
        List<String> headers = getOriginRequest().getHeaders().get(name);
        if(CollectionUtils.isEmpty(headers)) {
            return null;
        }
        return headers.get(0);
    }

    @Override
    public HttpRequest getOriginRequest() {
        return (HttpRequest) super.getOriginRequest();
    }

    @Override
    public List<String> getHeaders(String name) {
        return getOriginRequest().getHeaders().get(name);
    }

    @Override
    public void setHeader(String name, String value) {
        super.setHeader(name, value);
        getOriginRequest().getHeaders().set(name, value);
    }

    @Override
    public String getRequestURL() {
        return getOriginRequest().getURI().toString();
    }

    @Override
    public String getRequestURI() {
        return getOriginRequest().getURI().getPath();
    }

    @Override
    public HttpMethod getMethod() {
        return getOriginRequest().getMethod();
    }

    @Override
    public String getMethodValue() {
        return getOriginRequest().getMethodValue();
    }

    @Override
    public URI getURI() {
        return getOriginRequest().getURI();
    }

    @Override
    public HttpHeaders getHeaders() {
        return getOriginRequest().getHeaders();
    }
}
